package mspbots.cw.business.core.teams;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.business.core.BaseReceiver;
import mspbots.cw.common.ResultMsg;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * @author Jay.Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class TeamsReceiver extends BaseReceiver {

    private final TeamsRepository teamsRepository;

    @RabbitListener(queues = "connect-wise.teams.tl")
    public void process(ResultMsg resultMsg) {
        JsonNode entity = resultMsg.getEntity();
        Teams data = super.objectMapper.convertValue(entity, Teams.class);
        data.setId(null);
        data.setTeamId(resultMsg.getId());
        data.setTenantCode(resultMsg.getTenantId());
        data.setSyncTime(resultMsg.getSyncDate());

        data.setLeaderId(super.getLongValueId(entity.get("leader")));
        data.setLeaderName(super.getStringValueName(entity.get("leader")));
        data.setDepartmentId(super.getLongValueId(entity.get("department")));
        data.setDepartmentName(super.getStringValueName(entity.get("department")));
        data.setLocationId(super.getLongValueId(entity.get("location")));
        data.setLocationName(super.getStringValueName(entity.get("location")));
        data.setDateEntered(super.getDateTimeValue(entity.findValue("dateEntered")));
        data.setLastUpdated(super.getDateTimeValue(entity.findValue("lastUpdated")));

        this.teamsRepository.findByTeamIdAndTenantCode(resultMsg.getId(), resultMsg.getTenantId())
                .map(result -> {
                    data.setId(result.getId());
                    return data;
                })
                .defaultIfEmpty(data)
                .flatMap(this.teamsRepository::save).block(Duration.ofSeconds(10));
    }
}
